package com.goushu.controller;

import com.goushu.pojo.Cart;
import com.goushu.pojo.Result;
import com.goushu.service.CartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/cart")
@Slf4j
public class CartController {

    @Autowired
    private CartService cartService;

    /**
     * 获取购物车列表
     * @return
     */
    @GetMapping
    public Result<List<Cart>> listCart() {
        List<Cart> lc = cartService.listCart();
        return Result.success(lc);
    }

    /**
     * 加入购物车操作
     * @param id
     * @param count
     * @return
     */
    @PostMapping("/add")
    public Result addCart(Integer id, Integer count) {
        Cart c = cartService.checkCartExist(id);
        // 如果不存在，新插入，如果存在，修改数量
        if(c == null) {
            cartService.addCart(id, count);
        } else {
            count += c.getCount();
            cartService.updateCount(id, count);
        }

        return Result.success();
    }

    /**
     * 修改购物车操作
     * @param cart
     * @return
     */
    @PutMapping("/modify")
    public Result modifyCart(@RequestBody Cart cart) {
        cartService.modifyCart(cart);
        return Result.success();
    }

    /**
     * 删除购物车操作
     * @param id
     * @return
     */
    @PostMapping("/delete")
    public Result deleteCart(Integer id) {
        cartService.deleteCart(id);
        return Result.success();
    }
}
